package counter.until;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {

	
	public static void addUtil(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Cookie[] cookies = request.getCookies();
		Cookie counter =null;
		if(cookies !=null){
			for(Cookie c:cookies){
				if(c.getName().equals("counter")){
					counter = c;
					break;
				}
			}
		}
		if(counter ==null){
			counter = new Cookie("counter","1");
		}else{
			Integer count = Integer.parseInt(counter.getValue());
			count++;
			counter.setValue(count.toString());
		}
		response.addCookie(counter);
		request.setAttribute("count", counter.getValue());
		
		
		ServletContext context =request.getServletContext();
		if(context.getAttribute("allcount")!=null){
			int count =(Integer)context.getAttribute("allcount");
			count++;
			context.setAttribute("allcount",count);
		}else{
			context.setAttribute("allcount", 1);
		}
	}
	
	
}
